package com.ruicar.afs.cloud.apply.pre.loan.mq.sender.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruicar.afs.cloud.apply.business.mq.config.ArchiveConfig;
import com.ruicar.afs.cloud.apply.business.service.ArchiveMQService;
import com.ruicar.afs.cloud.apply.common.entity.ApplyConditionApproval;
import com.ruicar.afs.cloud.apply.common.entity.ApplyContractInfo;
import com.ruicar.afs.cloud.apply.common.entity.ApplyOrderInfo;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConstants;
import com.ruicar.afs.cloud.apply.contract.service.ApplyContractInfoService;
import com.ruicar.afs.cloud.apply.pre.loan.condition.ApplyConditionApprovalCondition;
import com.ruicar.afs.cloud.apply.pre.loan.mq.sender.CaseSubmitInfoSender;
import com.ruicar.afs.cloud.apply.pre.loan.mq.sender.service.ConditionApprovalMessageSenderSerevice;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyConditionApprovalService;
import com.ruicar.afs.cloud.apply.pre.loan.service.impl.ApplyOrderInfoServiceImpl;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinCostDetails;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyCostDetailsService;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.dto.mq.approve.ConditionalApprovalReturnInfo;
import com.ruicar.afs.cloud.common.mq.rabbit.message.AfsTransEntity;
import com.ruicar.afs.cloud.image.entity.ComAttachmentFile;
import com.ruicar.afs.cloud.image.entity.ComAttachmentManagement;
import com.ruicar.afs.cloud.image.service.ComAttachmentFileService;
import com.ruicar.afs.cloud.image.service.ComAttachmentManagementService;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * 附條件核准 MQ controller
 *
 * @author 耿继辉
 */
@RestController
@AllArgsConstructor
@Slf4j
@RequestMapping("/sendConditionMQ")
@ConditionalOnProperty(prefix = "com.ruicar.afs.cloud.mq.rabbit", name = "enable")
public class ConditionApprovalMessageController {
    private final CaseSubmitInfoSender caseSubmitInfoSender;
    private final ConditionApprovalMessageSenderSerevice senderSerevice;
    private final ApplyOrderInfoServiceImpl applyOrderInfoService;
    private final ApplyConditionApprovalService applyConditionApprovalService;
    private final ApplyCostDetailsService costDetailsService;
    private final ApplyContractInfoService applyContractInfoService;
    private final ArchiveMQService archiveMQService;
    private final ComAttachmentManagementService comAttachmentManagementService;
    private final ComAttachmentFileService comAttachmentFileService;

    /**
     * 附條件核准MQ
     *
     * @param condition
     * @return
     */
    @PostMapping("/sendConditionApprovalMessage")
    @ApiOperation("附條件核准結果MQ發送")
    @Transactional(rollbackFor = Exception.class)
    public IResponse sendConditionApprovalMessage(@RequestBody ApplyConditionApprovalCondition condition) throws ParseException {
        String applyNo = condition.getApplyNo();
        ApplyOrderInfo orderInfoByApplyNo = applyOrderInfoService.getOrderInfoByApplyNo(applyNo);
        //将订单状态更新
        if (Boolean.TRUE.toString().equals(condition.getResult())) {
            if (ObjectUtil.isNotNull(orderInfoByApplyNo)) {
                orderInfoByApplyNo.setApplyStatus(ApplyConstants.APPLY_STATUS_PASS);
                orderInfoByApplyNo.setRiskPassDate(new Date());
                //更新订单为核准
                applyOrderInfoService.updateById(orderInfoByApplyNo);
            }
            //在合同表内插入一条数据
            ApplyContractInfo contractInfo = this.applyContractInfoService.getContractInfoByAppplyNo(applyNo);
            if (contractInfo == null) {
                ApplyContractInfo applyContractInfo = new ApplyContractInfo();
                applyContractInfo.setApplyNo(applyNo);
                applyContractInfo.setContractNo(applyNo + "-001");
                applyContractInfo.setContractStatus(ApplyConstants.CONTRACT_STATUS_01);
                applyContractInfo.setCreateTime(new Date());
                applyContractInfo.setCreateBy("");
                this.applyContractInfoService.save(applyContractInfo);
            }
            List<FinCostDetails> costDetailsList = this.costDetailsService.getCostDetailsList(applyNo);
            String before = JSONArray.toJSONString(costDetailsList);
            //查询附条件核准表数据
            ApplyConditionApproval approval = this.applyConditionApprovalService.getOne(Wrappers.<ApplyConditionApproval>query()
                    .lambda().eq(ApplyConditionApproval::getApplyNo, applyNo));
            if (ObjectUtil.isNotNull(approval)) {
                JSONObject content = JSONObject.parseObject(approval.getApproveContent());
                List<FinCostDetails> finCostDetailsList = content.getJSONArray("finCostDetailsList").toJavaList(FinCostDetails.class);
                //更新版本
                if (CollectionUtil.isNotEmpty(finCostDetailsList)) {
                    finCostDetailsList.forEach(finCostDetails -> {
                        //查询融资信息
                        List<FinCostDetails> costDetailsList1 = costDetailsService.getCostDetailsList(finCostDetails.getApplyNo());
                        if (CollectionUtil.isNotEmpty(costDetailsList1)) {
                            costDetailsList1.forEach(finCostDetails1 -> {
                                if (finCostDetails.getCostType().equals(finCostDetails1.getCostType())) {
                                    //更新融资信息
                                    finCostDetails.setId(finCostDetails1.getId());
                                    this.costDetailsService.updateById(finCostDetails);
                                }
                            });
                        }
                    });
                }
            }
            //变更后融资信息
            List<FinCostDetails> detailsList = this.costDetailsService.getCostDetailsList(applyNo);
            String after = JSONArray.toJSONString(detailsList);
            if (StringUtil.isEmpty(approval.getVersion())) {
                approval.setVersion(ApplyConstants.ONE);
            } else {
                Long aLong = Long.valueOf(approval.getVersion());
                aLong++;
                approval.setVersion(String.valueOf(aLong));
            }
            approval.setBeforeParameter(before);
            approval.setAfterParameter(after);
            this.applyConditionApprovalService.updateById(approval);
        } else if (Boolean.FALSE.toString().equals(condition.getResult())) {
            orderInfoByApplyNo.setApplyStatus(ApplyConstants.APPLY_STATUS_REFUSE);
            orderInfoByApplyNo.setCancelDate(new Date());
            //订单拒绝,推送拒绝信息至归档(申请废弃)
            archiveMQService.archivePushMQ(String.valueOf(orderInfoByApplyNo.getId()), null, orderInfoByApplyNo.getApplyNo(), ArchiveConfig.wworder_refuse);
            //附条件核准拒绝
            applyOrderInfoService.updateById(orderInfoByApplyNo);
        }
        AfsTransEntity<ConditionalApprovalReturnInfo> entity = senderSerevice.returnMessage(applyNo);
        this.caseSubmitInfoSender.conditionApprovalMessageSender(entity);
        return IResponse.success("附条件结果发送成功");
    }
}
